package com.token.sysflow.hander;
import com.token.base.Pl;
import com.token.sql.IntegrateSql;
import com.token.sql.PrepareSql;

import java.sql.ResultSet;
import java.util.HashMap;

/**
 * @author chenjianxiong 2020/5/23
 */
public class Authorize {

    public Authorize() {

    }

    /**
     * 获取被授权人
     * @param iSql
     * @param approvers
     * @param appKeyId
     * @return Map:<授权人，被授权人>
     * @throws Exception
     */
    public HashMap<String,String> getAuthorized(IntegrateSql iSql, String[] approvers, String appKeyId) throws Exception{
        int length = approvers.length;
        HashMap<String,String> map = new HashMap<>(length);
        StringBuffer sql = new StringBuffer(100);
        sql.append("SELECT Authorizer,Authorized FROM v_AuthorizationInfo WHERE Status=1 AND AppKeyId=? AND SysId=? ");
        if(length == 1){
            sql.append(" AND Authorizer='").append(approvers[0]).append("'");
            map.put(approvers[0],"");
        }else{
            StringBuilder appr = new StringBuilder(50);
            boolean b = false;
            for(String approver:approvers){
                if(!approver.equals("")) {
                    if (b) {
                        appr.append(",");
                    }

                    appr.append("'").append(approver).append("'");
                    map.put(approver, "");
                    b = true;
                }
            }
            sql.append(" AND Authorizer IN(").append(appr).append(")");
        }

        PrepareSql psql = new PrepareSql(iSql);
        psql.setPrepare(sql);
        psql.setPstValue(1,appKeyId);
        psql.setPstValue(2, Pl.getSysId());
        ResultSet rs = psql.executeQuery();
//        System.out.println(appKeyId+ "-->sql = " + sql);
        if(rs.next()){
            do{
                map.put(rs.getString("Authorized"),rs.getString("Authorizer"));
                System.out.println(rs.getString("Authorizer") + "授权给" + rs.getString("Authorized") );
            }while(rs.next());
        }
        rs.close();
        psql.close();
        return map;
    }

}
